<template>
	<div class="app">
		<div class="title">Login</div>
		<form @submit="formSubmit" class="form-login">
			<div class="form-input">
				<div class="input-img">
					<img class="input-image" src="@/assets/images/username.png" />
				</div>
				<input type="text" class="input-content" placeholder="请输入用户名" placeholder-style="color: #c7c7c7;"
					maxlength='20' name="username" />
			</div>
			<div class="form-input">
				<div class="input-img">
					<img class="input-image" src="@/assets/images/password.png" />
				</div>
				<input type="password" class="input-content" placeholder="请输入密码" placeholder-style="color: #c7c7c7;"
					maxlength='20' name="password" />
			</div>
			<div class="form-remember">
				<div class="register" @click="register">注册账号</div>
			</div>
			<button class="form-button" form-type="submit">登录</button>
		</form>
		<div v-if="tip" class="tip-layer">
			<div class="tip">{{tipContent}}</div>
		</div>
	</div>
</template>

<script>
	import axios from 'axios';
	import {
		showTips
	} from '@/assets/js/common.js';
	export default {
		name: 'login',
		data() {
			return {
				httpUrl: 'http://qgm1.fengjian123.com/service9501/',
				tipContent: '',
				tip: 0,
			};
		},
		mounted() {
			this.isLogin();
		},
		methods: {
			isLogin() {
				const sessionData = window.sessionStorage.getItem('users');
				const userData = JSON.parse(sessionData);
				if (sessionData == null) {
					this.$router.push('/login');
					console.log("登录失效");
					return;
				}

				axios.get(this.httpUrl + 'user/getUser', {
						headers: {
							'Authorization': 'Bearer ' + userData.token,
							'Content-Type': 'application/json',
						},
					})
					.then(res => {
						console.log(res);
						if (res.data.err == 0) {
							this.$router.push('/my');
						}
					})
					.catch(error => {
						console.error("登录失败，请检查网络", error);
						showTips(this, '登录失败，请检查网络');
						this.$router.push('/login');
						return;
					});
			},
			formSubmit(e) {
				e.preventDefault();
				const formData = new FormData(e.target);
				const username = formData.get('username');
				const password = formData.get('password');
				const usernameRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
				const passwordRegex = /^(?=.*[A-Za-z])(?=.*\d)[A-Za-z\d]{6,20}$/;
				if (!usernameRegex.test(username) || !passwordRegex.test(password)) {
					showTips(this, '用户名和密码格式不正确');
					return;
				}

				axios.post(this.httpUrl + 'user/login', {
						username,
						password
					})
					.then(res => {
						sessionStorage.setItem('users', JSON.stringify(res.data.user));
						if (res.data.err == 0) {
							showTips(this, '登录成功');

							const userId = res.data.user.id;
							axios.post(this.httpUrl + 'shop/getCart', null, {
									headers: {
										'Authorization': 'Bearer ' + res.data.user.token,
										'Content-Type': 'application/json',
									},
									params: {
										userId
									}
								})
								.then(res => {
									let cartList = res.data.cartList;
									let cartArr = [];
									if (cartList.length > 0) {
										for (let i = 0; i < cartList.length; i++) {
											cartArr.push({
												productId: cartList[i].goods_id,
												buyNum: cartList[i].num,
												name: cartList[i].name,
												price: cartList[i].price,
												pay: cartList[i].num * cartList[i].price,
												selected: cartList[i].selected,
											});
										}
										sessionStorage.setItem('cart_' + userId, JSON.stringify(cartArr));
									}
								})
								.catch(error => {
									console.error("登录失败，请检查网络", error);
									showTips(this, '登录失败，请检查网络');
								});

							setTimeout(() => {
								this.$router.push('/my');
							}, 1000);
						} else {
							showTips(this, res.data.msg);
							console.log(res.data.msg);
						}
					})
					.catch(error => {
						console.error("登录失败，请检查网络", error);
						showTips(this, '登录失败，请检查网络');
					});
			},
			register: function() {
				this.$router.push('/register');
			}
		},
	}
</script>

<style scoped>
	@import url('@/assets/css/login-index.css');
</style>